package com.house.quartz.task;

import com.house.common.core.domain.entity.House;
import com.house.common.core.domain.entity.User;
import com.house.common.core.email.MailSender;
import com.house.common.utils.DateUtils;
import com.house.common.utils.StringUtils;
import com.house.system.domain.Contract;
import com.house.system.domain.Pay;
import com.house.system.mapper.ContractMapper;
import com.house.system.mapper.HouseMapper;
import com.house.system.mapper.PayMapper;
import com.house.system.mapper.UserMapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.List;

/**
 * 定时任务调度
 */
@Component("houseTask")
@Slf4j
public class HouseTask {

    @Autowired
    private ContractMapper contractMapper;

    @Autowired
    private HouseMapper houseMapper;

    @Autowired
    private PayMapper payMapper;

    @Autowired
    private UserMapper userMapper;

    @Autowired
    private MailSender sender;

    public void createNewPay() {
        //找到所有生效中的合同
        List<Contract> contracts = contractMapper.selectEffectContract();

        for (Contract contract : contracts) {
            Pay pay = new Pay();
            //获取house
            House house = houseMapper.selectHouseByHouseId(contract.getHouseId());
            pay.setPayPrice(house.getRentalPrice());

            pay.setHouseId(contract.getHouseId());
            pay.setUserId(contract.getbUserId());
            pay.setCreateTime(DateUtils.getNowDate());
            pay.setStatus("0");

            //插入缴费单
            payMapper.insertPay(pay);

            //发送邮件提醒
            User user = userMapper.selectUserByUserId(contract.getbUserId());
            String subject = "租金缴纳提醒";
            String text = "尊敬的用户" + user.getNickName() + ",请按时缴纳房屋" + house.getHouseName() + "的租金";
            sender.sendSimpleMail(user.getNickName(), house.getHouseName(), user.getEmail(), text, subject);
            log.info("已发送提醒用户{}缴纳房屋{}租金的邮件", user.getNickName(), house.getHouseName());

        }
    }
}
